import React from 'react';
import {Button, Dropdown, Menu} from 'antd';
import {MoreOutlined} from '@ant-design/icons';
import BaseComp from "../Base/BaseComp";
import PropTypes from "prop-types";
import {assign, isFunction, map, pick} from "lodash-es";
import ButtonComp from "../ButtonComp";

/**
 * 普通按钮组
 */
export default class ButtonGroup extends BaseComp {

    static propTypes = {
        ...BaseComp.propTypes,
        text: PropTypes.string,
        type: PropTypes.string,
        size: PropTypes.string,
        ghost: PropTypes.bool,
        shape: PropTypes.string,
        buttons: PropTypes.arrayOf(PropTypes.object)
    };

    initState(props) {
        const {appins} = this.props;
        return {
            disabled: false,
            visible: appins && isFunction(appins.setBtnInsById)
        }
    }

    componentDidMount() {
        super.componentDidMount();

        // 将此按钮的实例保存到 appins 中，用于在需要时，手动控制此组件的逻辑
        const {appins} = this.props;
        if (appins && isFunction(appins.setBtnInsById)) {
            setTimeout(() => {
                this.setState({visible: false});
            }, 0)
        }
    }

    renderMenu() {
        const {buttons, appins, customprops} = this.props;
        return (
            <Menu>
                {
                    map(buttons, (btn, ind) => (
                        <Menu.Item key={btn.id || ind}>
                            {/*{btn}*/}
                            <ButtonComp
                                {...btn}
                                appins={appins}
                                customprops={customprops}
                                text={btn.text || btn.name}
                            />
                        </Menu.Item>
                    ))
                }
            </Menu>
        )
    }

    mainRender(context) {
        const {buttons, text, children, appins, customprops, id, componentType, ...restProps} = this.props;
        const finalChildren = this.props.children || text || null;
        const fStyleO = assign({}, restProps.style, this.state.compMoreProps.style);
        const moreProps = {
            ...restProps,
            disabled: this.getPropsByName('disabled') || false,
            ...this.state.compMoreProps,
            style: fStyleO
        };
        const menu = this.renderMenu();

        return <Dropdown
            overlay={menu}
            placement="topCenter"
            visible={this.state.visible}
            onVisibleChange={visible => {
                this.setState({visible});
            }}
        >
            <Button
                {...moreProps}
            >{finalChildren} <MoreOutlined /></Button>
        </Dropdown>
    };

}